import React, { Component } from 'react';     
import { Form,Row,Col,Button,Modal,message,Tag,Select } from 'antd';
import '../index.css';
import SelectFileForm2 from '../../../components/Modal/select-file-form2';
// import SelectCurveUpForm from '../../Modal/select-curvesUp-form';
import {reqAllMb,reqProcessMbData,reqProcessDocDataList,reqCurvesTranslation} from '../../../api';
import { connect } from 'react-redux';
import {replaceNewCurves2,isUpdatePages,getDaosMb2,setMbInReducer,setEditDepthData2,getCurvesIntoDao2,setDocInReducer,returnInit2,initmbData} from '../../../redux/actions';
import {setDocDataList} from '../../../utils/storageUtils';



//import {DaosListDemo2} from '../../../config/daosList';  
//const docDatasList1 = DaosListDemo2;
//const docDatasList2 = JSON.parse(JSON.stringify(DaosListDemo2));

const { Option } = Select;


class DataComparisonSider extends Component {
  
  state = {
    docInfo1: '',  
    docInfo2: '',    
    visible: '0',
    mb_id:'',  // 选中模板id
    mbList:[],   // 所有模板列表
    curves_mb:[],  // 获取模板内容
  };

  getAllMb = async() => {
    const result = await reqAllMb();
    //console.log("mb11",result);
    if(result.code === 200){
      const mbList = result.data;
      this.setState({
        mbList
      })
    }  
  }
  
  getMb = (values) => {  // 选择模板进行state保存
    this.setState({
      mb_id: values
    })
  }

  handleMb = async() => {   // 选择模板，并导入
    const mb_id = this.state.mb_id; 
    const result = await reqProcessMbData(mb_id);   
    if(result.code === 200){
      // console.log("获取模板成功",result)
      this.setState({
        docInfo1 : '',
        docInfo2 : ''
      })
      var curves_mb = result.data.mb_dao;
      this.props.initmbData({});
      curves_mb.map((item) => {
        if(item.curves){
          item.curves.map((item1) => {
            const itemCopy = JSON.parse(JSON.stringify(item1));
            itemCopy['curve_name'] = item1.curve_name + "1";
            itemCopy['title'] = item1.title + "1";
            item.curves.push(itemCopy);
          })
        }  
      })
      curves_mb.map(item=>{
        item.id=Math.random()
      })
      this.setState({
        curves_mb   // 数据对比 独有的模板形式
      })
      this.props.getDaosMb2(curves_mb);   // 将道模板先加载到页面中
      this.props.setMbInReducer(result.data);  // 保存当前模板(完整的) :  result.data
      this.props.isUpdatePages(!this.props.updatePages);  // 及时更新页面(导入模板页面)
    }else{
      message.error("模板获取失败！");
    }  
  }
  
  openFileShow1 = () => {    // 选择上曲线 弹框显示
    this.setState({
      visible: '1'
    });
  };
  handleOpenFile1 = () => {    // 选择文件1 响应函数 
    this.setState({ visible: '0' });
    var docInfo1;
    const doc_id = this.formRef1.current.getFieldValue('doc_id');
    this.docList1.map((item) => {
      if(item.doc_id === doc_id){
        docInfo1 = item
      }
    });
    this.setState({
      docInfo1
    });
  }; 

  openFileShow2 = () => {    // 选择下曲线 弹框显示
    this.setState({
      visible: '2'
    });
  };
  handleOpenFile2 = () => {    // 选择下曲线 响应函数 
    this.setState({ visible: '0' });
    var docInfo2;
    const doc_id = this.formRef2.current.getFieldValue('doc_id');
    this.docList2.map((item) => {
      if(item.doc_id === doc_id){
        docInfo2 = item
      }
    });
    this.setState({
      docInfo2
    },() => this.handleCurves())   // 将曲线整合，放入道中
       
  };
  
  handleCurves = async() => {
    const {docInfo1,docInfo2} = this.state;
    var docDatasList = {} 
    var docDatasList1,docDatasList2;
    var docStartDepth,docEndDepth,docInterval = 0.1;  // 合并文件的起深、终深、间隔；
    var startSupplement,endSupplement,startSupplementCount,endSupplementCount;  // 起终深不一致时，深度差值，为了修改xData
    var yData = [];
    if(docInfo1.doc_type === "纯数据文件" && docInfo2.doc_type === "纯数据文件"){
      const result1 = await reqProcessDocDataList(docInfo1.doc_id,docInfo1.doc_type,docInfo1.drill_id,docInfo1.org_id,docInfo1.ws_id);  // 根据文件id 获取 纯数据文件1
      const result2 = await reqProcessDocDataList(docInfo2.doc_id,docInfo2.doc_type,docInfo2.drill_id,docInfo2.org_id,docInfo2.ws_id);  // 根据文件id 获取 纯数据文件2
      console.log("duibi",result1,result2)
      if(result1.code === 200 && result2.code === 200){  // 两个文件都获取成功 
        if(result1.data.interval === result2.data.interval){  // 两个文件的 深度间隔必须一致,否则无法展示！！
          docInterval = result1.data.interval;
          docDatasList1 = JSON.parse(JSON.stringify(result1.data));
          docDatasList2 = JSON.parse(JSON.stringify(result2.data));
          if(docDatasList1.rock_curve){  // 处理 文件1
            docDatasList1.curves.push(docDatasList1.rock_curve);    // 将岩性曲线 推入 曲线数组中
          }
          if(docDatasList2.rock_curve){  // 处理 文件2
            docDatasList2.curves.push(docDatasList2.rock_curve);    // 将岩性曲线 推入 曲线数组中
            docDatasList2.curves.map((item) => {   // 修改 曲线名+1
              item.curve_name = item.curve_name + '1';
            })
          }
          // 2、处理 深度区间，找起深、终深，以及修改对应的 xData
          if(docDatasList1.start_depth = docDatasList2.start_depth){   // 处理起深：找小值
            docStartDepth = docDatasList1.start_depth;
          }else if(docDatasList1.start_depth < docDatasList2.start_depth){  // 给 docDatasList2 的xData插值
            docStartDepth = docDatasList1.start_depth;
            startSupplement = docDatasList2.start_depth - docDatasList1.start_depth;  
            // 修改 docDatasList2 的起始深度差值xData
            startSupplementCount = startSupplement / docInterval;  // 差值数量
            docDatasList2.curves.map((item) => {   // xdata插值
              for(let i = 0; i < startSupplementCount; i++){
                item.xData.unshift('');   // 数组前插0,(插0有漏洞，插一个'')
              }
            })
          }else{   // 给 docDatasList1 的xData插值
            docStartDepth = docDatasList2.start_depth;
            startSupplement = docDatasList1.start_depth - docDatasList2.start_depth;  
            // 修改 docDatasList1 的起始深度差值xData
            startSupplementCount = startSupplement / docInterval;  // 差值数量
            docDatasList1.curves.map((item) => {   // xdata插值
              for(let i = 0; i < startSupplementCount; i++){
                item.xData.unshift('');   // 数组前插0,(插0有漏洞，插一个'')
              }
            })
          }

          if(docDatasList1.end_depth = docDatasList2.end_depth){   // 处理终深：找大值
            docEndDepth = docDatasList1.end_depth;
          }else if(docDatasList1.end_depth > docDatasList2.end_depth){  // 给 docDatasList2 的xData插值
            docEndDepth = docDatasList1.end_depth;
            endSupplement = docDatasList1.end_depth - docDatasList2.end_depth;  
            // 修改 docDatasList2 的起始深度差值xData
            endSupplementCount = endSupplement / docInterval;  // 差值数量
            docDatasList2.curves.map((item) => {   // xdata插值
              for(let i = 0; i < endSupplementCount; i++){
                item.xData.push('');   // 数组前插0,(插0有漏洞，插一个'')
              }
            })
          }else{   // 给 docDatasList1 的xData插值
            docEndDepth = docDatasList2.end_depth;
            endSupplement = docDatasList2.end_depth - docDatasList1.end_depth;  
            // 修改 docDatasList1 的起始深度差值xData
            endSupplementCount = endSupplement / docInterval;  // 差值数量
            docDatasList1.curves.map((item) => {   // xdata插值
              for(let i = 0; i < endSupplementCount; i++){
                item.xData.push('');   // 数组前插0,(插0有漏洞，插一个'')
              }
            })
          }
          this.props.setEditDepthData2(Number(docStartDepth),Number(docEndDepth),Number(docInterval));   // 更新文件的 起深、终深、深度间隔，并更新

          // 3、生成新的yData
          for (let i = docStartDepth; i <= docEndDepth; i+=docInterval) {   //i+=0.1
            yData.push(Number(i.toFixed(2)));  
          }
          // 4、两个文件处理完毕，生成新的docDatasList，并进行展示
          docDatasList["curves"] = docDatasList1.curves.concat(docDatasList2.curves);  // 合并两个文件的曲线；
          docDatasList["start_depth"] = docStartDepth; 
          docDatasList["end_depth"] = docEndDepth; 
          docDatasList["interval"] = docInterval;
          docDatasList["doc_id1"] = docDatasList1.doc_id;
          docDatasList["doc_id2"] = docDatasList2.doc_id;
          docDatasList["yData"] = yData;
          console.log("wenjian1",docDatasList1,docDatasList2,docDatasList);

          if(docDatasList.curves){ 
            if(this.state.curves_mb.length != 0){  // 用户在选择文件之前已经导入模板
              const data = docDatasList.curves;
              this.props.getCurvesIntoDao2(data);  // 将 纯数据曲线 传入模板中  vvvvvvvvv
              this.props.setDocInReducer(docDatasList);  // 将文件保存到reducer  vvvvvvvv
              //this.props.isUpdatePages(!this.props.updatePages);  // 及时更新页面(导入模板页面)
              setDocDataList(docDatasList);  // 将获取到的 文件数据 放入内存  
            }else{  // 用户没有选择模板
              message.error("请先选择模板!");
            }
          }
        }else{
          message.error("文件深度间隔不一致，无法展示！")
        }
      }else if(result1.code !== 200){
        message.error("文件1获取失败，请重新选择！");
      }else if(result2.code !== 200){
        message.error("文件2获取失败，请重新选择！");
      }
    }
  }
  
  handleCancel = () => {    // 对话框取消按钮
    this.setState({
      visible: '0'
    }); 
  };

  onFinish1 = async(values) => {   // 提交表单，获取平移后的曲线 并 更新
    const {docData} = this.props;
    console.log("-----",this.props.docData)
    if(docData.doc_id1 && docData.doc_id2){
      var curves = this.props.selectedCurves2;   // 需要平移的曲线集合
      var yData = this.props.docData.yData;
      const depthMove = values.move_depth;  
      console.log("数据对比平移",curves,yData,depthMove);    // 在docData中将曲线找出，docId和docType不用先留着
      const result = await reqCurvesTranslation(curves,yData,depthMove);  // 获取平移后的曲线
      if(result.code === 200){
        console.log("平移结果2",result.data);
        this.props.replaceNewCurves2(result.data);   // 更新处理后的曲线（daosDataList）
      }else{
        message.error(result.data);
      }  
    }else{
      message.error("请先导入文件！");
    } 
  };

  componentWillMount(){
    this.getAllMb();
  }

  formRef1 = React.createRef(); 
  // formRef2 = React.createRef(); 
  // formRef3 = React.createRef(); 
  formRef4 = React.createRef(); 

  componentWillUpdate(nextProps){
    if(this.props.isDoNull != nextProps.isDoNull){   // 清空
      this.formRef1.current.resetFields();
      // this.formRef2.current.resetFields();
      // this.formRef3.current.resetFields();
      // this.formRef4.current.resetFields();
      document.getElementById('input1').innerHTML = ' ';
      document.getElementById('input2').innerHTML = ' ';
      this.props.returnInit2([]);  // 清空选中的曲线
    }
  }


  render() {
    const { visible,docInfo1,docInfo2,mbList} = this.state;
    return (
      <div className='data-comparison-sider-wrapper'>
        <Row>
        <div className="show-select-line">
          <p className="select-line">曲&nbsp;&nbsp;&nbsp;&nbsp;线：</p>
          <div className="select-box">
            {this.props.selectedCurves2.map((item) => <Tag>{item.title}</Tag>)}  
          </div>
        </div>
        </Row>
        
        
        <Row>
          <Col style={{ width: 70, lineHeight: '32px' }}>模&nbsp;&nbsp;&nbsp;&nbsp;版：</Col>
          <Col>
          <Form ref={this.formRef1}  >
            <Form.Item 
              name='mb' 
            >
              <Select 
                style={{ width: 110 }} 
                placeholder="请选择" 
                getPopupContainer={triggerNode => triggerNode.parentNode}
                onSelect={this.getMb}
              >  
                {mbList.map((item,index) => <Option value={item.mb_id} key={index}>{item.mb_name}</Option>)}
              </Select>
            </Form.Item> 
            </Form>
          </Col>
          <Col>
            <Form.Item>
              <Button className="data-pre-process-button"  type="primary" onClick={this.handleMb}>
                确定
              </Button>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col style={{ width: 70, lineHeight: '32px' }}>文&nbsp;件&nbsp;1：</Col>
          <Col>
          {/* <Form ref={this.formRef2}  >
            <Form.Item 
              name='file1' 
            >
              {console.log("文件1",docInfo1.title)}
              <Input className="data-pre-process-input" id="input1" value={docInfo1.title} style={{width:'112px',height:'28px'}} readonly />
            </Form.Item> 
            </Form> */}
            <div className="data-pre-process-input" id="input1" >{docInfo1.title}</div>
          </Col>
          <Col>
            <Form.Item>
              <Button className="data-pre-process-button"  type="primary" onClick={this.openFileShow1}>
                选择
              </Button>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col style={{ width: 70, lineHeight: '32px' }}>文&nbsp;件&nbsp;2：</Col>
          <Col>
          {/* <Form ref={this.formRef3}  >
            <Form.Item 
              name='file2' 
            >
              {console.log("下曲线",docInfo1.title)}
              <Input className="data-pre-process-input" id="input2" value={docInfo2.title} style={{width:'112px',height:'28px'}} readonly />
            </Form.Item> 
            </Form> */}
            <div className="data-pre-process-input" id="input2" >{docInfo2.title}</div>
          </Col>
          <Col>
            <Form.Item>
              <Button className="data-pre-process-button" type="primary" onClick={this.openFileShow2}>
                选择
              </Button>
            </Form.Item>
          </Col>
        </Row>
          
        
        {/* <Form
            name="control-ref" 
            onFinish={this.onFinish1}
          >
          <Row style={{marginBottom: 10}}>

            <Col>平 &nbsp; 移：</Col>
            <Col>
              <Form.Item 
                className="data-config-form"  
                name="move_depth"
                rules={[{
                  pattern: /^[-+]?[0-9]+$/,  // pattern正则表达式匹配
                  message: ' ',  //请输入数字
                }]}    
              >
                <InputNumber defaultValue={0}  className="data-pre-process-input" />
              </Form.Item>  
            </Col>
            <Col>
              <Form.Item>
                <Button className="data-pre-process-button" type="primary" htmlType="submit">
                  确定
                </Button>
              </Form.Item>
            </Col> 
          </Row>
        </Form> */}
        


        <Modal
          title="选择文件1"
          visible={visible === '1'}
          onOk={this.handleOpenFile1}
          onCancel={this.handleCancel}
          destroyOnClose={true}  // 关闭时销毁子元素
          okText="确定"
          cancelText="取消"
        >
          <SelectFileForm2 setForm = {(formRef) => {this.formRef1 = formRef}}  setDocList = {(docList) => {this.docList1 = docList}} /> 
        </Modal>

        <Modal
          title="选择文件2"
          visible={visible === '2'}
          onOk={this.handleOpenFile2}
          onCancel={this.handleCancel}
          destroyOnClose={true}  // 关闭时销毁子元素
          okText="确定"
          cancelText="取消"
        >
          <SelectFileForm2 setForm = {(formRef) => {this.formRef2 = formRef}}  setDocList = {(docList) => {this.docList2 = docList}} /> 
        </Modal>
    </div>
    );
  }
}

export default  connect(
  state => ({selectedCurves2: state.selectedCurves2, docData: state.docData, updatePages: state.updatePages, isDoNull: state.isDoNull}),
  {getDaosMb2,setMbInReducer,setEditDepthData2,getCurvesIntoDao2,setDocInReducer,replaceNewCurves2,returnInit2,initmbData,isUpdatePages}    //replaceNewCurves,isUpdatePages,
)(DataComparisonSider);












 
